package com.sgy.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author Administrator
 * @date 2025/8/24 16:57
 * @description
 */
public class NIOServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 打开服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 绑定对应的端口
        serverSocketChannel.bind(new InetSocketAddress(9999));

        // 通道默认是阻塞，需要设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务端启动成功...");
        while (true) {
            // 检查是否有客户端连接，有客户端连接会返回对应的通道
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null) {
                System.out.println("没有客户端连接...");
                Thread.sleep(2000);
                continue;
            }
            // 获取客户端传递过来的数据，并把数据放在byteBuffer缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 返回值
            // 整数：本地读到有效字节数
            // 0：没有读取到数据
            // -1：表示读到末尾
            int read = socketChannel.read(byteBuffer);
            System.out.println("客户端消息：" + new String(byteBuffer.array(), 0, read, "UTF-8"));

            // 给客户端回写数据
            socketChannel.write(ByteBuffer.wrap("hello client".getBytes(StandardCharsets.UTF_8)));

            // 释放资源
            socketChannel.close();
        }
    }
}
